﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace LogicWaveWpf.UC
{
    public partial class SquareWaveControl : UserControl
    {
        static SquareWaveControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(
                typeof(SquareWaveControl),
                new FrameworkPropertyMetadata(typeof(SquareWaveControl)));
        }

        // 频率依赖属性
        public static readonly DependencyProperty FrequencyProperty =
            DependencyProperty.Register("Frequency", typeof(double), typeof(SquareWaveControl),
            new PropertyMetadata(1.0, OnWavePropertyChanged));

        // 占空比依赖属性
        public static readonly DependencyProperty DutyCycleProperty =
            DependencyProperty.Register("DutyCycle", typeof(double), typeof(SquareWaveControl),
            new PropertyMetadata(0.5, OnWavePropertyChanged));

        public double Frequency
        {
            get => (double)GetValue(FrequencyProperty);
            set => SetValue(FrequencyProperty, value);
        }

        public double DutyCycle
        {
            get => (double)GetValue(DutyCycleProperty);
            set => SetValue(DutyCycleProperty, value);
        }

        private static void OnWavePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            (d as SquareWaveControl)?.InvalidateVisual();
        }

        protected override void OnRender(DrawingContext dc)
        {
            base.OnRender(dc);

            double width = ActualWidth;
            double height = ActualHeight;
            double period = width / Frequency;
            double highDuration = period * DutyCycle;

            var pen = new Pen(Foreground, 1);
            double yHigh = height * 0.2;
            double yLow = height * 0.8;

            for (double x = 0; x < width; x += period)
            {
                // 上升沿
                dc.DrawLine(pen, new Point(x, yLow), new Point(x, yHigh));
                // 高电平
                dc.DrawLine(pen, new Point(x, yHigh), new Point(x + highDuration, yHigh));
                // 下降沿
                dc.DrawLine(pen, new Point(x + highDuration, yHigh),
                            new Point(x + highDuration, yLow));
                // 低电平
                if (x + period < width)
                    dc.DrawLine(pen, new Point(x + highDuration, yLow),
                                new Point(x + period, yLow));
            }
        }
    }




}
